//
//  SSDKSwitchUtil.m
//  SuperSDK
//
//  Created by 涂俊 on 2017/11/6.
//  Copyright © 2017年 WYHT. All rights reserved.
//

#import "SSDKSwitchUtil.h"
#import "SSDKDataHelper.h"
#import "SSDKHttpUtil.h"

@implementation SSDKSwitchUtil

//服务器端配置的开关，缓存在DataHelper的SwitchConfig下
static NSString *SWITCH_DATA = @"SwitchConfig";

+ (void) valueWithKey : (NSString *) key
             delegate : (void (^)(id value))delegate {
    NSMutableDictionary *switchCongfigs = [SSDKDataHelper dataValueWithKey:SWITCH_DATA];
    if (switchCongfigs == nil) {
        //请求服务器，获取开关配置
        NSLog(@"本地开关配置为空，请求服务器");
        [SSDKSwitchConfigUtil postWithHttpDelegate: ^(SSDKBaseResData* resData) {
            if ([resData isOk]) {
                //开关获取成功
                NSLog(@"请求服务器开关ok:%@", resData.data);
                [SSDKDataHelper setDataValue:resData.data forKey:SWITCH_DATA];
                if (delegate) {
                    delegate([resData.data valueForKey:key]);
                }
            } else {
                //开关获取失败，存入空dictionary
                NSLog(@"请求服务器开关fail:%@", [resData error]);
                [SSDKDataHelper setDataValue:[[NSMutableDictionary alloc] init] forKey:SWITCH_DATA];
            }
        }];
    } else {
        if (delegate) {
            delegate([switchCongfigs valueForKey:key]);
        }
    }
}

+ (void) allValueWithDelegate : (void (^)(NSDictionary *value))delegate {
    NSMutableDictionary *switchCongfigs = [SSDKDataHelper dataValueWithKey:SWITCH_DATA];
    if (switchCongfigs == nil) {
        //请求服务器，获取开关配置
        NSLog(@"本地开关配置为空，请求服务器");
        [SSDKSwitchConfigUtil postWithHttpDelegate: ^(SSDKBaseResData* resData) {
            if ([resData isOk]) {
                //开关获取成功
                NSLog(@"请求服务器开关ok:%@", resData.data);
                [SSDKDataHelper setDataValue:resData.data forKey:SWITCH_DATA];
                if (delegate) {
                    delegate(resData.data);
                }
                return;
            } else {
                //开关获取失败，存入空dictionary
                NSLog(@"请求服务器开关fail:%@", [resData error]);
                [SSDKDataHelper setDataValue:[[NSMutableDictionary alloc] init] forKey:SWITCH_DATA];
            }
        }];
    } else {
        if (delegate) {
            delegate(switchCongfigs);
        }
    }
}

@end
